package wec_wallet.ebo.com.activity;


import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.doublewave.DoubleWaveView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bassproject.ebo.com.ebobass.activity.MyBaseActivity;
import bassproject.ebo.com.ebobass.application.Phone;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.http_utils.utils.Ipost;
import wec_wallet.ebo.com.utils.URLs;
import bassproject.ebo.com.ebobass.utils.CacheUtility;
import bassproject.ebo.com.ebobass.utils.IDeviceId;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.bean.UserInfo;
import wec_wallet.ebo.com.common.Constant;
import wec_wallet.ebo.com.common.Constants;
import wec_wallet.ebo.com.common.SharedPreference;
import wec_wallet.ebo.com.intercept.PhoneListenService;
import wec_wallet.ebo.com.util.PermissionsChecker;
import wec_wallet.ebo.com.util.StringUtil;
import wec_wallet.ebo.com.utils.Functions;

/**
 * 安全主界面
 * Created by Administrator on 2018/3/8.
 */

public class SafetyActivity extends MyBaseActivity {


    @BindView(R.id.frame_safety)
    FrameLayout frameLayout;
    @BindViews({
            R.id.tv_safety_top,
            R.id.tv_safety_grade,
            R.id.tv_safety_01,
            R.id.tv_safety_02,
            R.id.tv_safety_03,
            R.id.tv_safety_04,

            R.id.tv_safetyError_01,
            R.id.tv_safetyError_02,
            R.id.tv_safetyError_03,
            R.id.tv_safetyError_04,
            R.id.tv_safety_talkLater,

    })
    List<TextView> tvList;
    @BindView(R.id.waveView)
    DoubleWaveView waveView;


    @BindViews({
            R.id.linear_close,
            R.id.linear_testing,
            R.id.linear_safety_bottom
    })
    List<LinearLayout> linearList;
    @BindView(R.id.img_safety_top)
    ImageView img_top;
    @BindView(R.id.btn_safety_stop)
    Button btn_stop;
    String userId;
    boolean flag;
    boolean flag_02 = false;
    IHttpPostListener phoneListener = new IHttpPostListener() {
        @Override
        public void onTimeOut() {

        }

        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            if (!TextUtils.isEmpty(result)) {
                JSONObject resultObject = null;
                try {
                    resultObject = new JSONObject(result);
                    String error = resultObject.getString("error");
                    if (resultObject.has("is_auth") && (resultObject.getString("is_auth")).equals
                            ("0")) {
                        IToast.show(resultObject.getString("error_msg"));
                        Functions.relogin(SafetyActivity.this);//登录过期

                        return;
                    }
                    if (error.equals("0")) {
                        JSONArray data = resultObject.getJSONArray("data");
                        for (int i = 0; i < data.length(); i++) {
                            Phone phone = new Phone();
                            phone.setPhone(data.getString(i));
                            Phone.insertdata(phone);
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    IHttpPostListener postListener = new IHttpPostListener() {
        @Override
        public void onTimeOut() {

        }

        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            if (!TextUtils.isEmpty(result)) {
                JSONObject resultObject = null;
                try {
                    resultObject = new JSONObject(result);

                    String error = resultObject.getString("error");
                    if (resultObject.has("is_auth") && (resultObject.getString("is_auth")).equals
                            ("0")) {
                        IToast.show(resultObject.getString("error_msg"));
                        Functions.relogin(SafetyActivity.this);//登录过期
                        return;
                    }
                    if (resultObject.has("error_msg")) {
                        IToast.show(resultObject.getString("error_msg"));
                        return;
                    }
                    if (error.equals("0")) {
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                StringUtil.tvDrableLeft(getApplicationContext(), tvList.get(7),
                                        R.drawable.img_correct);
                                tvList.get(8).setVisibility(View.VISIBLE);
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        StringUtil.tvDrableLeft(getApplicationContext(),
                                                tvList.get(8),
                                                R.drawable.img_correct);
                                        tvList.get(9).setVisibility(View.VISIBLE);
                                        new Handler().postDelayed(new Runnable() {
                                            public void run() {
                                                StringUtil.tvDrableLeft(getApplicationContext(),
                                                        tvList.get(9),
                                                        R.drawable.img_correct);

                                            }
                                        }, 2000);


                                    }
                                }, 2000);
                            }
                        }, 2000);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        }
    };
    IHttpPostListener postListener1 = new IHttpPostListener() {
        @Override
        public void onTimeOut() {

        }

        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            if (!TextUtils.isEmpty(result)) {
                UserInfo json = JSON.parseObject(result, UserInfo.class);
                if (json.getIs_auth() != null && json.getIs_auth() == 0) {
                    Functions.relogin(SafetyActivity.this);
                } else {
                    if (json.getError() == 0) {
                        Log.e("-", "id-" + json.getEquipment_id());
                        if (!StringUtil.isStringEmpty(json.getEquipment_id())) {
                            flag_02 = true;
                        }

                        setIsOpen();
                    }
                }
            }

        }
    };
    private PhoneListenService service = null;
    private boolean isBound = false;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            isBound = true;
            service = ((PhoneListenService.MyBinder) binder).getService();


        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false;
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_safety);
        ButterKnife.bind(this);
        userId = I_Share.readAccountUserid();
        initViews();
        registerPhoneStateListener();


    }

    @Override
    public void initViews() {
        tvList.get(10).getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        waveView.setAnim(false);

        getInfo();
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("id", "1");
        Functions.post(this, Constant.URL_GETPHONE, postParams, phoneListener, false, false);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        setIsOpen();
        boolean flag_01 = SharedPreference.getIsOpenIntercept(this
                , userId);
        if (flag_01) {
            if (!isBound) {
                registerPhoneStateListener();
            }
        } else {
            if (isBound) {
                unbindService(conn);
                isBound = false;
            }
        }
    }

    private void setIsOpen() {
        //判断是否开启了一键开启
//        boolean isOpen = SharedPreference.getIsOpen(this,
//                userId);
        boolean flag_01 = SharedPreference.getIsOpenIntercept(this
                , userId);
        boolean flag_03 = CacheUtility.spGetOut(this, Constants.SAFETY_OPEN + userId, false);
        boolean flag_04 = CacheUtility.spGetOut(this, Constants.RAMCLEAN_OPEN + userId, false);
//        boolean flag_02 = CacheUtility.spGetOut(this, Constants.SERIALNUM_OPEN + userId, false);
        Log.e("=-", "=-flag:" + flag_02);
        if (flag_01 && flag_02 && flag_03 && flag_04) {
            tvList.get(2).setText(getString(R.string.security_details));
            tvList.get(3).setText(getString(R.string.security_details));
            tvList.get(4).setText(getString(R.string.security_details));
            tvList.get(5).setText(getString(R.string.security_details));
            tvList.get(0).setText(getString(R.string.security_protection));
            tvList.get(1).setText("Lv.4");

        } else {
            int count = 0;
            if (flag_01) {
                count += 1;
                tvList.get(2).setText(getString(R.string.security_details));
            } else {
                tvList.get(2).setText(getString(R.string.security_close));
            }
            if (flag_02) {
                count += 1;
                tvList.get(3).setText(getString(R.string.security_details));
            } else {
                tvList.get(3).setText(getString(R.string.security_close));
            }
            if (flag_03) {
                count += 1;
                tvList.get(4).setText(getString(R.string.security_details));
            } else {
                tvList.get(4).setText(getString(R.string.security_close));
            }
            if (flag_04) {
                count += 1;
                tvList.get(5).setText(getString(R.string.security_details));
            } else {
                tvList.get(5).setText(getString(R.string.security_close));
            }
            tvList.get(1).setText("Lv." + count);
            tvList.get(0).setText(getString(R.string.security_opening));
//            SharedPreference.putOpen(getApplicationContext(), userId, false);
        }
    }

    @OnClick({
            R.id.frame_safety,
            R.id.rela_safety_intercept,
            R.id.rela_safety_serialNum,
            R.id.rela_safety_safetyTest,
            R.id.rela_safety_RAMClean,
            R.id.tv_safety_right,
            R.id.tv_safety_talkLater,
            R.id.btn_safety_stop
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.frame_safety:
                waveView.setAnim(true);
                setImg(img_top, 8000);
                break;
            case R.id.rela_safety_intercept:
                startActivityForResult(new Intent(getApplicationContext(), InterceptActivity
                        .class), 001);
                break;
            case R.id.rela_safety_serialNum:
                if (I_Share.isLogin()) {
                    startActivityForResult(new Intent(getApplicationContext(), SerialNumberActivity
                            .class), 002);
                } else {
                    Functions.relogin(this);
                }
                break;
            case R.id.rela_safety_safetyTest:
                if (I_Share.isLogin()) {
                    startActivityForResult(new Intent(getApplicationContext(), SafetyTestActivity
                            .class), 003);
                } else {
                    Functions.relogin(this);
                }
                break;
            case R.id.rela_safety_RAMClean:
                if (I_Share.isLogin()) {
                    startActivityForResult(new Intent(getApplicationContext(), RAMCleanActivity
                            .class), 004);
                } else {
                    Functions.relogin(this);
                }

                break;
            case R.id.tv_safety_right:
                startActivity(new Intent(getApplicationContext(), MineActivity
                        .class));
                break;
            case R.id.tv_safety_talkLater://点击以后再说
                linearList.get(1).setVisibility(View.GONE);
                linearList.get(0).setVisibility(View.VISIBLE);
                setTextView(View.GONE, R.drawable.img_error);
                frameLayout.setClickable(true);
                setIsOpen();
                break;
            //停止
            case R.id.btn_safety_stop:
                flag = true;
                img_top.clearAnimation();

                break;
        }
    }

    /**
     * 一键启动动画效果
     *
     * @param img
     * @param time
     */
    private void setImg(ImageView img, int time) {
        AnimationSet animationSet = new AnimationSet(true);
        RotateAnimation rotateAnimation;
        rotateAnimation = new RotateAnimation(0f, 359f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(time);
        animationSet.addAnimation(rotateAnimation);
        animationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                tvList.get(0).setText(getString(R.string.security_detecting));
                linearList.get(0).setVisibility(View.GONE);
                linearList.get(2).setVisibility(View.GONE);
                linearList.get(1).setVisibility(View.VISIBLE);
                tvList.get(6).setVisibility(View.VISIBLE);
                btn_stop.setVisibility(View.VISIBLE);

                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        StringUtil.tvDrableLeft(getApplicationContext(), tvList.get(6),
                                R.drawable.img_correct);
                        tvList.get(7).setVisibility(View.VISIBLE);
                        toggleBlockGroup();

                    }
                }, 2000);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (flag) {
                    linearList.get(0).setVisibility(View.VISIBLE);
                    linearList.get(1).setVisibility(View.GONE);
                    setIsOpen();
                    flag = false;
                } else {
                    tvList.get(0).setText(getString(R.string.security_protection));
                    linearList.get(1).setVisibility(View.VISIBLE);
                    linearList.get(0).setVisibility(View.GONE);
                    frameLayout.setClickable(false);
                    btn_stop.setVisibility(View.GONE);
                    Log.e("-","flag_02:"+flag_02);
                    if (flag_02) {
                        flag_02 = false;
                    } else {
                        flag_02 = true;
                    }
                    setLocalData(true);
                    setTextView(View.VISIBLE, R.drawable.img_correct);
                }
                waveView.setAnim(false);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        img.startAnimation(animationSet);
    }

    private void setLocalData(boolean isTrue) {
        String[] primissions = {Manifest.permission.READ_PHONE_STATE};
        if (PermissionsChecker.lacksPermissions(SafetyActivity.this, primissions)) {
            PermissionsChecker.showMissingPermissionDialog(SafetyActivity.this, 2001, getString(R
                    .string.help), getString(R.string.string_help_text), primissions);
            SharedPreference.putOpenIntercept(getApplicationContext(), userId, false);
        } else {
            SharedPreference.putOpenIntercept(getApplicationContext(), userId, isTrue);
            Intent intent = new Intent(this, PhoneListenService.class);
            intent.setAction(PhoneListenService.ACTION_REGISTER_LISTENER);
            startService(intent);
        }
        CacheUtility.spSave(getApplicationContext(), Constants.SAFETY_OPEN +
                userId, isTrue);
        CacheUtility.spSave(getApplicationContext(), Constants.RAMCLEAN_OPEN +
                userId, isTrue);
//        CacheUtility.spSave(getApplicationContext(), Constants.SERIALNUM_OPEN +
//                userId, isTrue);
    }

    private void setTextView(int flag, int drable) {
        tvList.get(6).setVisibility(flag);
        StringUtil.tvDrableLeft(getApplicationContext(), tvList.get(6),
                drable);
        tvList.get(7).setVisibility(flag);
        StringUtil.tvDrableLeft(getApplicationContext(), tvList.get(7),
                drable);
        tvList.get(8).setVisibility(flag);
        StringUtil.tvDrableLeft(getApplicationContext(), tvList.get(8),
                drable);
        tvList.get(9).setVisibility(flag);
        StringUtil.tvDrableLeft(getApplicationContext(), tvList.get(9),
                drable);
        linearList.get(2).setVisibility(flag);
    }

    private void toggleBlockGroup() {
        if (I_Share.isLogin()) {
            Map<String, Object> postParams = new HashMap<String, Object>();
            postParams.put("equipment_id", IDeviceId.getDeviceID());
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", userId);
            Functions.post(this, URLs.Mobile_bind, postParams, postListener, false, true);
        } else {
            Functions.relogin(this);
        }
    }

    private void getInfo() {
        if (I_Share.isLogin()) {
            Map<String, Object> postParams = new HashMap<String, Object>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());

//            postParams.put("lan", I_Share.getLanguageType_String());
            Functions.post(this, URLs.User_Info, postParams, postListener1, true, true);
        } else {
            finish();
        }


    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 2001) {
            Intent intent = new Intent(this, PhoneListenService.class);
            intent.setAction(PhoneListenService.ACTION_REGISTER_LISTENER);
            startService(intent);
        }
    }

    private void registerPhoneStateListener() {
        boolean isOpen = SharedPreference.getIsOpenIntercept(getApplicationContext(), I_Share
                .readAccountUserid());
        if (isOpen) {
            String[] primissions = {Manifest.permission.READ_PHONE_STATE};
            if (PermissionsChecker.lacksPermissions(this, primissions)) {
                PermissionsChecker.showMissingPermissionDialog(this, 2001, getString(R.string
                        .help), getString(R.string.string_help_text), primissions);
            } else {
                Intent intent = new Intent(this, PhoneListenService.class);
                intent.setAction(PhoneListenService.ACTION_REGISTER_LISTENER);
                bindService(intent, conn, Context.BIND_AUTO_CREATE);
            }
        } else {
        }
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    protected void onDestroy() {
        if (isBound) {
            unbindService(conn);
        }
        super.onDestroy();
    }
}
